package net.contrend.system.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import net.contrend.system.dao.RoleDao;
import net.contrend.system.form.RoleForm;
import net.contrend.util.BaseAction;

public class RoleAction extends BaseAction {
    
    private RoleDao roleDao;
    
    private void initDao() {
        if (null == this.roleDao) {
            this.roleDao = (RoleDao) this.getBean("roleDao");
        }
    }
    
    public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        DynaActionForm df = (DynaActionForm) form;
        RoleForm role = (RoleForm) df.get(this.ACTION_FORM_NAME);
        int i = this.roleDao.insert(role);
        request.setAttribute("ACTION_RESULT", i);
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
    public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        DynaActionForm df = (DynaActionForm) form;
        RoleForm role = (RoleForm) df.get(this.ACTION_FORM_NAME);
        int i = this.roleDao.update(role);
        request.setAttribute("ACTION_RESULT", i);
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        String roleId = request.getParameter("roleId");
        int i = this.roleDao.delete(roleId);
        response.getWriter().write(String.valueOf(i));
        
        return null;
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        this.initDao();
        
        String roleId = request.getParameter("roleId");
        DynaActionForm df = (DynaActionForm) form;
        df.set(this.ACTION_FORM_NAME, this.roleDao.query(roleId));
        
        return mapping.findForward(this.ACTION_PAGE_EDIT);
    }
    
}
